"ui";
importClass(android.graphics.drawable.GradientDrawable.Orientation);
importClass(android.graphics.drawable.GradientDrawable);
importClass(java.io.FileOutputStream);
importClass(java.net.URL);
ui.layout(
    <vertical padding="16">
        <button id="longBottom" text="下载准备就绪" w="*"/>
    </vertical>
);
//初始化gradientDrawable
let gradientDrawable = new GradientDrawable()
let colorArr = [colors.GREEN, colors.TRANSPARENT]
gradientDrawable.setCornerRadius(30);
// log(gradientDrawable.setColors.toString())
gradientDrawable.setStroke(5, colors.parseColor("#000000"));
gradientDrawable.setOrientation(GradientDrawable$Orientation.LEFT_RIGHT);
ui.longBottom.setBackground(gradientDrawable);
//初始化下载参数
running = false
byteSum = 0; //总共读取的文件大小
byteRead = 0; //每次读取的byte数
buffer = util.java.array('byte', 1024); //byte[]
var url = 'http://app.p4p.sogou.com/1/18535407/3414511/e808ddce765ce08903d4d20e87ca54f2/dhxy_os11265218574.apk?c=1afe4929d7496833c7bec8ce3cea98b2';
var filePath = files.path("./ajPro_8.8.20.apk");
//按钮监听
ui.longBottom.on("click", () => {
    if (running) {
        toast("已经在冲了🚀")
        return
    }
    if (files.exists(filePath)) {
        ui.longBottom.text("下载完成")
        gradientDrawable.setColors(colorArr, [1, 0]);
        ui.longBottom.setBackground(gradientDrawable);
        app.viewFile(filePath)
        return
    }
    toast("注意你的流量哦")
    progress = 0
    running = true
    //开始下载
    let setProgress = setInterval(() => {
        gradientDrawable.setColors(colorArr, [progress, 0]);
        ui.longBottom.text("下载进度" + (progress * 100).toFixed(1) + "%")
        ui.longBottom.setBackground(gradientDrawable);
        if (progress >= 1) {
            running = false
            clearInterval(setProgress)
            ui.longBottom.text("下载完成")
            app.viewFile(filePath)
        }
    }, 20)
    threads.start(function() {
        var myUrl = new URL(url);
        var conn = myUrl.openConnection(); //URLConnection
        inStream = conn.getInputStream(); //InputStream
        fs = new FileOutputStream(filePath); //FileOutputStream
        connLength = conn.getContentLength(); //int
        while ((byteRead = inStream.read(buffer)) != -1) {
            byteSum += byteRead;
            fs.write(buffer, 0, byteRead); //读取
            progress = byteSum / connLength;
        }
    })
});